import React, { useState, memo, useEffect } from 'react';
import History from '@/components/History';

import defaultAvatar from '@res/avatar.jpeg';
import { useAppSelector } from '@/store/hooks';
import { useDispatch } from 'react-redux';
import { fetchDonkey } from '@/store/slices/userSlice';
import { useHistory, useParams } from 'react-router';
import { motion } from 'framer-motion';
import { useCallback } from 'react';
import api, { listTask } from '../../api';

const MemoHistory = memo(History);

function Home() {
  const history = useHistory();
  const [count, setCount] = useState(0);
  const [tasks, setTasks] = useState<Task[]>([]);
  const uuid = useAppSelector((state) => state.user.uuid);
  const dispatch = useDispatch();
  useEffect(() => {
    listTask().then((e) => {
      const { data } = e;
      setTasks(data);
    });
  }, []);
  const createTask = useCallback(() => {
    const newTaskName = prompt('请输入新项目名称');
    if (!newTaskName) return;
    api.createTask(newTaskName).then((e) => {
      console.log('创建成功', e.data);
    });
    console.log('New task name', newTaskName);
  }, []);

  return (
    <div className="dashboard">
      <header className="dashboard-header">
        <h1 className="dashboard-title" onClick={() => dispatch(fetchDonkey())}>
          基于云算法库的隐私保护系统
        </h1>
        <div className="dashboard-action">
          <img
            className="dashboard-avatar"
            src="//placekitten.com/200/200"
          ></img>
        </div>
      </header>
      <div className="history-list">
        {tasks.map(({ id, taskName, createTime, updateTime, uuid }) => (
          <MemoHistory
            key={id}
            projectName={taskName}
            onClick={(e) => {
              history.push(`/task/${uuid}/init/config`);
            }}
            updateTime={updateTime ?? ''}
          />
        ))}
        <motion.a whileHover={{ scale: 1.1 }}>
          <div className="history create-task" onClick={createTask}>
            + 创建任务
          </div>
        </motion.a>
      </div>
    </div>
  );
}

export default Home;
